<template>
  <div v-if="store && store.delete === 1" class="error-state">
    <i class="fas fa-exclamation-circle fa-3x"></i>
    <p>商店不存在或已下架</p>
    <router-link to="/" class="back-btn">返回首页</router-link>
  </div>
  <div class="store-detail-page" v-else-if="store && !loading">
    <div class="navbar">
      <a @click="goBack" class="navbar-back">
        <i class="fas fa-arrow-left"></i>
      </a>
      <div class="navbar-title">商店详情</div>
      <div style="width: 24px;">
        <i class="fas fa-heart favorite-icon" :class="{ 'favorited': isFavorited }" @click="toggleFavorite"></i>
      </div>
    </div>

    <div class="store-banner">
      <img :src="store.coverImage" :alt="store.name">
      <div class="banner-overlay">
        <div class="store-name">{{ store.name }}</div>
      </div>
    </div>

    <div class="store-info">
      <div class="store-info-row">
        <div class="store-info-label"><i class="fas fa-star"></i></div>
        <div class="store-info-content">{{ store.rating.toFixed(1) == 0 ? '暂无评分' : store.rating.toFixed(1) }} ({{ reviews.length }}条评价)</div>
      </div>
      <div class="store-info-row">
        <div class="store-info-label"><i class="fas fa-map-marker-alt"></i></div>
        <div class="store-info-content">{{ store.address }}</div>
        <button @click="navigateToStore" class="navigation-button">导航</button>
      </div>
      <div class="store-info-row">
        <div class="store-info-label"><i class="fas fa-clock"></i></div>
        <div class="store-info-content">营业时间: {{ store.businessHours }}</div>
      </div>
      <div class="store-info-row">
        <div class="store-info-label"><i class="fas fa-phone-alt"></i></div>
        <div class="store-info-content">联系电话: {{ store.phone }}</div>
      </div>
    </div>

    <div class="tab-bar">
      <div class="tab" :class="{ active: activeTab === 'products' }" @click="selectTab('products')">商品</div>
      <div class="tab" :class="{ active: activeTab === 'services' }" @click="selectTab('services')">服务</div>
      <div class="tab" :class="{ active: activeTab === 'reviews' }" @click="selectTab('reviews')">评价</div>
      <div class="tab" :class="{ active: activeTab === 'info' }" @click="selectTab('info')">商家</div>
    </div>

    <div class="container">
      <!-- 商品标签页 -->
      <div id="tab-products" class="tab-content" :class="{ active: activeTab === 'products' }">
        <div class="product-section" v-for="group in groupedProducts" :key="group.name">
          <div class="section-title">
            <span>{{ group.name }}</span>
            <router-link :to="{ name: 'StoreProductListAll', params: { storeId: store.storeId }, query: { category: group.categoryId } }"
              class="section-more">查看全部 ></router-link>
          </div>
          <div class="product-list">
            <router-link :to="{ name: 'ProductDetail', params: { id: product.productId } }" class="product-card"
              v-for="product in group.products" :key="product.productId">
              <img class="product-image" :src="product.mainImage ? product.mainImage : '/image/store_cover/1.png'"
                :alt="product.name">
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-price">¥{{ product.price }}</div>
              </div>
            </router-link>
          </div>
        </div>
      </div>

      <!-- 服务标签页 -->
      <div id="tab-services" class="tab-content" :class="{ active: activeTab === 'services' }">
        <div class="service-list">
          <div class="service-item-row" v-for="service in services" :key="service.serviceId">
            <div class="service-icon">
              <i :class="service.icon || 'fas fa-star'"></i>
            </div>
            <div class="service-details">
              <div class="service-name-detail">{{ service.name }}</div>
              <div class="service-description">{{ service.description }}</div>
            </div>
            <div class="service-pricing">
              <div class="service-price">¥{{ service.price }}</div>
              <div class="service-duration" v-if="service.duration">{{ service.duration }} min</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 评价标签页 -->
      <div id="tab-reviews" class="tab-content" :class="{ active: activeTab === 'reviews' }">
        <div class="review-list">
          <div class="review-item" v-for="review in reviews" :key="review.reviewId">
            <div class="review-header">
              <img class="review-avatar" :src="review.user.avatar" alt="用户头像">
              <div class="review-user-info">
                <div class="review-username">{{ review.user.username }}</div>
                <div class="review-date">{{ review.createdAt }}</div>
              </div>
              <div class="review-rating">
                <i v-for="n in 5" :key="n"
                  :class="['fas', 'fa-star', { 'active': n <= review.rating }]"></i>
              </div>
            </div>
            <div class="review-content">{{ review.content }}</div>
            <div class="mentioned-product" v-if="review.product">
              <div class="product-image-container">
                <img :src="review.product.mainImage" alt="商品图片">
              </div>
              <div class="product-details">
                <div class="product-name">{{ review.product.name }}</div>
                <div class="product-price">¥{{ review.product.price }}</div>
              </div>
            </div>
            
          </div>
        </div>
      </div>

      <!-- 商家标签页 -->
      <div id="tab-info" class="tab-content" :class="{ active: activeTab === 'info' }">
        <div class="info-section">
          <h3 class="info-section-title">商家简介</h3>
          <p class="info-section-content">{{ store.description || '暂无简介' }}</p>
        </div>
        <div class="info-section">
          <h3 class="info-section-title">详细信息</h3>
          <div class="info-detail-list">
            <div class="info-detail-item">
              <i class="fas fa-map-marker-alt"></i>
              <span>{{ store.address }}</span>
            </div>
            <div class="info-detail-item">
              <i class="fas fa-clock"></i>
              <span>营业时间: {{ store.businessHours }}</span>
            </div>
            <div class="info-detail-item">
              <i class="fas fa-phone-alt"></i>
              <span>联系电话: {{ store.phone }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="height: 80px;"></div>
  </div>
  <div v-else class="loading-container">
    <i class="fas fa-spinner fa-spin"></i> Loading...
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import api from '@/network/api';
import { showToast, showDialog } from 'vant';

const route = useRoute();
const router = useRouter();
const storeId = Number(route.params.id);

const store = ref(null);
const products = ref([]);
const services = ref([]);
const reviews = ref([]);
const categories = ref([]);
const isFavorited = ref(false);

const loading = ref(true);
const error = ref(null);
const activeTab = ref('products');

const groupedProducts = computed(() => {
  if (!products.value.length || !categories.value.length) return [];

  const categoryMap = new Map();
  categories.value.forEach(cat => {
    categoryMap.set(cat.categoryId, { name: cat.name, products: [] });
  });

  products.value.forEach(product => {
    if (categoryMap.has(product.categoryId)) {
      categoryMap.get(product.categoryId).products.push(product);
    } else {
      if (!categoryMap.has('other')) {
        categoryMap.set('other', { name: '其他', products: [] });
      }
      categoryMap.get('other').products.push(product);
    }
  });

  return Array.from(categoryMap.values())
    .filter(group => group.products.length > 0)
    .map(group => ({ ...group, categoryId: products.value.find(p => p.categoryId === Array.from(categoryMap.keys()).find(key => categoryMap.get(key) === group))?.categoryId }));
});

const fetchStoreData = async () => {
  loading.value = true;
  error.value = null;
  try {
    // 首先只获取商店信息，检查是否下架
    const storeRes = await api.getStoreDetail(storeId);
    store.value = storeRes.data.data;
    
    // 如果商店已下架，则不加载其他数据
    if (store.value && store.value.delete === 1) {
      console.log("商店已下架:", storeId);
      loading.value = false;
      return;
    }
    
    // 商店未下架，加载其他数据
    const [productsRes, servicesRes, categoriesRes, reviewsRes ] = await Promise.all([
      api.getStoreProducts(storeId),
      api.getStoreServices(storeId),
      api.getCategories(),
      api.getStoreReviews(storeId)
    ]);

    products.value = productsRes.data.data;
    services.value = servicesRes.data.data;
    categories.value = categoriesRes.data.data;
    reviews.value = reviewsRes.data.data;
  } catch (e) {
    error.value = "Failed to load store data.";
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const selectTab = (tabName) => {
  activeTab.value = tabName;
};

const toggleFavorite = async () => {
  // 检查用户是否登录
  const token = localStorage.getItem('token');
  if (!token) {
    // 用户未登录，显示登录提示
    showDialog({
      title: '提示',
      message: '登录已过期，请重新登录',
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
    }).then(({ confirm }) => {
      if (confirm) {
        // 用户点击了"去登录"按钮
        router.push('/login');
      }
    });
    return;
  }

  try {
    if (isFavorited.value) {
      // 取消收藏
      const response = await api.removeFavorite('store', storeId);
      
      // 检查响应状态
      if (response && response.code === 100) {
        showToast('取消收藏成功');
        isFavorited.value = false;
      } else {
        // 显示错误消息
        showDialog({
          title: '提示',
          message: response?.message || '取消收藏失败，请重试',
        });
      }
    } else {
      // 添加收藏
      const response = await api.addFavorite('store', storeId);
      
      // 检查响应状态
      if (response && response.code === 100) {
        showToast('收藏成功');
        isFavorited.value = true;
      } else {
        // 显示错误消息
        showDialog({
          title: '提示',
          message: response?.message || '收藏失败，请重试',
        });
      }
    }
  } catch (err) {
    console.error("Failed to toggle favorite", err);
  }
};

const checkFavorite = async () => {
  try {
    const response = await api.checkFavorite('store', storeId);
    
    // 检查响应结构
    if (response && response.code === 100) {
      // 如果响应中的data存在或为true，表示已收藏
      isFavorited.value = !!response.data;
    } else {
      // API调用成功但状态不是100，默认未收藏
      isFavorited.value = false;
      console.log("Check favorite returned non-success code:", response?.code);
    }
  } catch (err) {
    // 出错时默认未收藏
    console.error("Failed to check favorite", err);
    isFavorited.value = false;
  }
};

const goBack = () => router.back();

const navigateToStore = () => {
  if (store.value && store.value.longitude && store.value.latitude) {
    router.push({
      name: 'Navigation',
      query: {
        longitude: store.value.longitude,
        latitude: store.value.latitude,
        storeName: store.value.name
      }
    });
  } else {
    showToast('无法获取店铺位置信息');
  }
};

onMounted(async () => {
  await fetchStoreData();
  await checkFavorite();
});
</script>

<style scoped>
.favorite-icon {
  color: #a0aec0; /* 默认灰色 */
  cursor: pointer;
  transition: color 0.3s;
}

.favorite-icon.favorited {
  color: #e53e3e; /* 收藏时的红色 */
}

.store-detail-page {
  background-color: #f8fafc;
  min-height: 100vh;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 50;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.navbar-back {
  cursor: pointer;
}

.navbar-title {
  font-size: 18px;
  font-weight: 600;
}

.store-banner {
  position: relative;
  height: 200px;
  margin-top: 57px;
}

.store-banner img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0));
  padding: 15px;
  display: flex;
  align-items: flex-end;
}

.store-name {
  color: white;
  font-size: 22px;
  font-weight: bold;
}

.store-info {
  padding: 15px;
  background-color: white;
  margin-bottom: 8px; /* Spacing from tab bar */
}

.store-info-row {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f1f5f9; /* Separator line */
}

.store-info-row:first-child {
  padding-top: 0;
}

.store-info-row:last-child {
  padding-bottom: 0;
  border-bottom: none;
}

.store-info-label {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  width: 24px;
  color: #3490dc; /* Themed icon color */
}

.store-info-label i {
  font-size: 16px;
}

/* Highlight for rating star */
.store-info-row:first-child .store-info-label {
  color: #f59e0b;
}

.store-info-content {
  font-size: 15px;
  color: #4a5568;
  flex: 1;
  line-height: 1.5;
}

/* Highlight for rating text */
.store-info-row:first-child .store-info-content {
  font-weight: 600;
  color: #1e293b;
}

.navigation-button {
  background-color: #3490dc;
  color: white;
  padding: 6px 14px;
  border-radius: 999px;
  border: none;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s ease-in-out;
}

.navigation-button:hover {
  background-color: #2779bd;
  transform: scale(1.05);
}

.tab-bar {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 15px;
  color: #718096;
  font-size: 14px;
  position: relative;
  cursor: pointer;
  transition: color 0.3s ease;
}

.tab.active {
  color: #3490dc;
  font-weight: 500;
}

.tab.active:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20%;
  right: 20%;
  height: 3px;
  background-color: #3490dc;
  border-radius: 1.5px;
}

.tab-content {
  display: none;
  padding: 15px;
}

.tab-content.active {
  display: block;
}

.product-section {
  background-color: #fff;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  margin-bottom: 16px;
}

.product-section:last-of-type {
    margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  margin: 0 0 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f1f5f9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-more {
  font-size: 13px;
  color: #3490dc;
  font-weight: 500;
  transition: color 0.2s ease;
}

.section-more:hover {
  color: #2779bd;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.product-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e2e8f0;
  text-decoration: none;
  color: inherit;
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.product-info {
  padding: 10px;
}

.product-name {
  font-weight: 500;
  font-size: 14px;
  color: #2d3748;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 14px;
  color: #e53e3e;
  font-weight: bold;
}

/* New Service List Styles */
.service-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.service-item-row {
  display: flex;
  align-items: center;
  background-color: white;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
}

.service-item-row:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.service-icon {
  width: 50px;
  height: 50px;
  background-color: #ebf4ff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
  color: #3490dc;
  margin-right: 15px;
  flex-shrink: 0;
}

.service-details {
  flex-grow: 1;
}

.service-name-detail {
  font-size: 16px;
  font-weight: 500;
  color: #2d3748;
}

.service-description {
  font-size: 14px;
  color: #718096;
  margin-top: 5px;
}

.service-pricing {
  text-align: right;
  flex-shrink: 0;
}

.service-price {
  font-size: 16px;
  font-weight: bold;
  color: #e53e3e;
}

.service-duration {
  font-size: 12px;
  color: #a0aec0;
  margin-top: 5px;
}

.review-list {
  margin-top: 10px;
}

.review-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
  border-bottom: none; /* Override previous style */
}

.review-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.review-header {
  display: flex;
  align-items: center;
}

.review-avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin-right: 12px;
}

.review-user-info {
  flex-grow: 1;
}

.review-username {
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.review-date {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.review-rating .fa-star {
  font-size: 14px;
  margin-left: 2px;
  color: #e0e0e0;
}

.review-rating .fa-star.active {
  color: #ffc107;
}

.review-content {
  margin-top: 12px;
  font-size: 14px;
  line-height: 1.6;
  color: #555;
}

.mentioned-product {
  margin-top: 12px;
  padding: 10px;
  background-color: #f7f7f7;
  border-radius: 10px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.mentioned-product .product-image-container {
  width: 50px;
  height: 50px;
  margin-right: 12px;
  flex-shrink: 0;
}

.mentioned-product .product-image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.mentioned-product .product-details {
  flex-grow: 1;
}

.mentioned-product .product-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.mentioned-product .product-price {
  font-size: 13px;
  color: #e53935;
  margin-top: 4px;
}

.review-product {
  margin-top: 8px;
  padding: 8px;
}

.review-product-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.review-product-name {
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  margin-top: 5px;
}

.review-product-price {
  font-size: 14px;
  color: #e53e3e;
  font-weight: bold;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  font-size: 18px;
  color: #718096;
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  color: #a0aec0;
}

.error-state i {
  margin-bottom: 15px;
}

.back-btn {
  margin-top: 15px;
  padding: 8px 16px;
  background-color: #3490dc;
  color: white;
  border-radius: 5px;
  text-decoration: none;
}

/* Info Tab Styles */
.info-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;
}

.info-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  padding-bottom: 12px;
  margin-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.info-section-content {
  font-size: 14px;
  color: #4a5568;
  line-height: 1.6;
}

.info-detail-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-detail-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #4a5568;
}

.info-detail-item i {
  width: 20px;
  text-align: center;
  margin-right: 10px;
  color: #718096;
}
</style>